const app = getApp();
const reviewApi = require('../../utils/reviewApi');
const { formatTime } = require('../../utils/util');

Page({
  data: {
    reviews: [],
    page: 0,
    size: 10,
    hasMore: true,
    loading: false,
    orderStatusMap: {
      0: '待付款',
      1: '待发货',
      2: '待收货',
      3: '已完成',
      4: '已取消'
    }
  },

  onLoad() {
    console.log('我的评价页面加载');
    this.loadReviews();
  },

  onShow() {
    console.log('我的评价页面显示');
  },

  onPullDownRefresh() {
    console.log('下拉刷新');
    this.setData({
      reviews: [],
      page: 0,
      hasMore: true
    }, () => {
      this.loadReviews().then(() => {
        wx.stopPullDownRefresh();
      });
    });
  },

  onReachBottom() {
    console.log('页面触底');
    if (this.data.hasMore && !this.data.loading) {
      this.loadReviews();
    }
  },

  loadMore() {
    console.log('点击加载更多');
    if (this.data.hasMore && !this.data.loading) {
      this.loadReviews();
    }
  },

  async loadReviews() {
    if (this.data.loading || !this.data.hasMore) return;

    try {
      console.log('开始加载我的评价列表');
      this.setData({ loading: true });
      const { page, size } = this.data;

      // 检查用户登录状态
      const userInfo = wx.getStorageSync('userInfo');
      if (!userInfo) {
        console.log('用户未登录，请先登录');
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/login/login'
          });
        }, 1500);
        return;
      }

      // 调用API获取我的评价列表
      console.log('调用getMyReviews，页码:', page, '每页大小:', size);
      const response = await reviewApi.getMyReviews(page, size);
      console.log('getMyReviews响应:', response);

      // 检查API响应
      if (!response.success) {
        console.error('加载评价失败:', response.message);
        wx.showToast({
          title: response.message || '加载失败',
          icon: 'none'
        });
        this.setData({ loading: false });
        return;
      }

      // 处理返回的数据
      const { content, last } = response.data;
      
      if (!content || !Array.isArray(content)) {
        console.error('API返回的数据格式不正确:', response.data);
        wx.showToast({
          title: '数据格式错误',
          icon: 'none'
        });
        this.setData({ loading: false });
        return;
      }

      console.log('获取到的评价数据条数:', content.length);
      // 格式化评价数据
      const newReviews = content.map(review => {
        console.log('处理评价数据:', review);
        // 确保各字段存在，处理日期和价格格式等
        return {
          ...review,
          createTime: this.formatDate(review.createTime || new Date()),
          productPrice: review.productPrice ? parseFloat(review.productPrice).toFixed(2) : '0.00',
          orderStatus: review.orderStatus || '已完成',
          imageUrls: review.imageUrls || []
        };
      });

      console.log('格式化后的评价数据:', newReviews);

      // 更新页面数据
      this.setData({
        reviews: page === 0 ? newReviews : [...this.data.reviews, ...newReviews],
        page: page + 1,
        hasMore: !last,
        loading: false
      });

      if (newReviews.length === 0 && page === 0) {
        console.log('没有评价数据');
        wx.showToast({
          title: '暂无评价数据',
          icon: 'none'
        });
      } else {
        console.log(`成功加载${newReviews.length}条评价数据`);
      }

    } catch (error) {
      console.error('加载评价异常:', error);
      wx.showToast({
        title: error.message || '加载失败，请稍后重试',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  },

  formatDate(dateStr) {
    if (!dateStr) return '';
    try {
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    } catch (error) {
      console.error('日期格式化错误:', error);
      return dateStr;
    }
  },

  goToProduct(e) {
    const { id } = e.currentTarget.dataset;
    console.log('跳转到商品详情, 商品ID:', id);
    wx.navigateTo({
      url: '/pages/product/product?id=' + id
    });
  },

  previewImage(e) {
    const { urls, current } = e.currentTarget.dataset;
    console.log('预览图片:', current);
    wx.previewImage({
      urls,
      current
    });
  },

  async handleLike(e) {
    // 检查用户是否登录
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    const { reviewid: reviewId } = e.currentTarget.dataset;
    const reviewIndex = this.data.reviews.findIndex(r => r.id === reviewId);
    
    if (reviewIndex === -1) {
      console.error('未找到对应的评价:', reviewId);
      return;
    }

    const review = this.data.reviews[reviewIndex];
    const isLiked = review.liked;

    try {
      console.log(`${isLiked ? '取消点赞' : '点赞'}评价, ID:`, reviewId);
      
      // 乐观更新UI
      const newReviews = [...this.data.reviews];
      newReviews[reviewIndex] = {
        ...review,
        liked: !isLiked,
        likesCount: isLiked ? Math.max(0, review.likesCount - 1) : review.likesCount + 1
      };
      
      this.setData({ reviews: newReviews });

      // 调用API进行点赞/取消点赞
      const response = isLiked 
        ? await reviewApi.unlikeReview(reviewId)
        : await reviewApi.likeReview(reviewId);
      
      console.log(`${isLiked ? '取消点赞' : '点赞'}响应:`, response);

      // 如果API调用失败，恢复原状态
      if (!response.success) {
        console.error(`${isLiked ? '取消点赞' : '点赞'}失败:`, response.message);
        
        // 恢复原状态
        newReviews[reviewIndex] = review;
        this.setData({ reviews: newReviews });
        
        wx.showToast({
          title: response.message || `${isLiked ? '取消点赞' : '点赞'}失败`,
          icon: 'none'
        });
      }
    } catch (error) {
      console.error(`${isLiked ? '取消点赞' : '点赞'}异常:`, error);
      
      // 恢复原状态
      const newReviews = [...this.data.reviews];
      newReviews[reviewIndex] = review;
      this.setData({ reviews: newReviews });
      
      wx.showToast({
        title: error.message || `${isLiked ? '取消点赞' : '点赞'}失败`,
        icon: 'none'
      });
    }
  }
}); 